package com.api.qfengx.data.hrm;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.weaver.qfengx.DaoUtils;
import com.weaver.qfengx.NumberUtils;
import com.weaver.qfengx.StringUtils;
import com.weaver.qfengx.config.DevModeConfig;
import com.weaver.qfengx.entity.Result;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.check.JobComInfo;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author Qfengx <qffg1998@126.com>
 * @Date 2021-08-05 14:51:01
 */
@Path("/qfengx/data/hrm")
public class DataHrmApi {

    private Map<String, Object> getBaseInfoMap(User user) {
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("id", user.getUID());
        dataMap.put("loginid", user.getLoginid());
        dataMap.put("lastname", user.getLastname());
        dataMap.put("language", user.getLanguage());
        dataMap.put("mobile", user.getMobile());
        dataMap.put("lastlogindate",  user.getLastlogindate());
        dataMap.put("loginip", user.getLoginip());
        dataMap.put("job", new JobComInfo().getJobName(user.getJobtitle()));
        return dataMap;
    }

    private void appendSubcomDeptInfo(Map<String, Object> dataMap, User user) throws Exception {
        // 根据父子关系获取分部列表
        int subCom = user.getUserSubCompany1();
        List<Map<String, Object>> subcomList = Lists.newArrayList();
        List<String> subcomids = Splitter.on(",").trimResults().omitEmptyStrings()
                .splitToList(new SubCompanyComInfo().getAllSupCompany(Integer.toString(subCom)));
        subcomids = Lists.newArrayList(subcomids.iterator());
        subcomids.add(Integer.toString(subCom));
        for (String subcom : subcomids) {
            SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", subcom);
            map.put("name", subCompanyComInfo.getSubCompanyname(subcom));
            subcomList.add(map);
        }
        int deptId = user.getUserDepartment();
        List<Map<String, Object>> deptList = Lists.newArrayList();
        List<String> deptIds = Splitter.on(",").trimResults().omitEmptyStrings()
                .splitToList(new DepartmentComInfo().getAllSupDepartment(Integer.toString(deptId)));
        deptIds = Lists.newArrayList(deptIds.iterator());
        deptIds.add(Integer.toString(deptId));
        for (String id : deptIds) {
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", id);
            map.put("name", departmentComInfo.getDepartmentname(id));
            deptList.add(map);
        }
        dataMap.put("subcompanys", subcomList);
        dataMap.put("departments", deptList);
    }

    /**
     * 获取当前的帐号信息
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/allinfo")
    @Produces(MediaType.APPLICATION_JSON)
    public String allinfo(@Context HttpServletRequest request,
                            @Context HttpServletResponse response) {
        try {
            String userid = request.getParameter("userid");
            User user;
            if (StringUtils.isEmpty(userid)) {
                user = HrmUserVarify.getUser(request, response);
            } else {
                user = User.getUser(Integer.parseInt(userid), 0);
            }
            Map<String, Object> dataMap = getBaseInfoMap(user);
            dataMap.put("isadmin", user.isAdmin());
            if (user.isAdmin()) {
                dataMap = getBaseInfoMap(user);
            } else { // 获取次帐号等信息
                // 补充当前用户的，分部，部门信息
                appendSubcomDeptInfo(dataMap, user);
                List<Map<String, String>> secAccountList
                        = DaoUtils.executeQueryToMapList("select id, subcompanyid1, departmentid from hrmresource where BELONGTO = ?", user.getUID());
                // 依次补充次帐号信息
                List<Map<String, Object>> secAccounts = Lists.newArrayList();
                for (Map<String, String> secAccount : secAccountList) {
                    User subUser = User.getUser(NumberUtils.parseInt(secAccount.get("id")), 0);
                    Map<String, Object> userDataMap = getBaseInfoMap(subUser);
                    appendSubcomDeptInfo(userDataMap, subUser);
                    secAccounts.add(userDataMap);
                }
                dataMap.put("secAccounts", secAccounts);
            }
            return JSON.toJSONString(Result.ok(dataMap));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }

    @POST
    @Path("/dept/id")
    @Produces(MediaType.APPLICATION_JSON)
    public String hrmDeptId(@Context HttpServletRequest request,
                            @Context HttpServletResponse response) {
        try {
            String outkey = request.getParameter("outkey");
//            String fixedToken = request.getParameter("fixed_token");
            if (StringUtils.isEmpty(outkey)) {
                return JSON.toJSONString(Result.paramErr());
            }
//            if (!StringUtils.equals(fixedToken, DevModeConfig.getPropConfig("api.fixed.token", "f808f256e8df4dfc9f1f90633b194a13").getValue())) {
//                return JSON.toJSONString(Result.tokenErr());
//            }
            Map<String, String> resMap = DaoUtils.executeQueryToMap("select id, departmentname , outkey, departmentcode from hrmdepartment where outkey = ?", outkey);
            if (resMap == null || resMap.isEmpty()) {
                return JSON.toJSONString(Result.fail("部门不存在"));
            }
            return JSON.toJSONString(Result.ok(resMap));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }

    @POST
    @Path("/subcom/id")
    @Produces(MediaType.APPLICATION_JSON)
    public String hrmSubcomId(@Context HttpServletRequest request,
                              @Context HttpServletResponse response) {
        try {
            String outkey = request.getParameter("outkey");
//            String fixedToken = request.getParameter("fixed_token");
            if (StringUtils.isEmpty(outkey)) {
                return JSON.toJSONString(Result.paramErr());
            }
//            if (!StringUtils.equals(fixedToken, DevModeConfig.getPropConfig("api.fixed.token", "f808f256e8df4dfc9f1f90633b194a13").getValue())) {
//                return JSON.toJSONString(Result.tokenErr());
//            }
            Map<String, String> resMap = DaoUtils.executeQueryToMap("select id, subcompanycode, subcompanyname, outkey from hrmsubcompany where outkey = ?", outkey);
            if (resMap == null || resMap.isEmpty()) {
                return JSON.toJSONString(Result.fail("分部不存在"));
            }
            return JSON.toJSONString(Result.ok(resMap));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }


    @POST
    @Path("/user/id")
    @Produces(MediaType.APPLICATION_JSON)
    public String hrmUserId(@Context HttpServletRequest request,
                            @Context HttpServletResponse response) {
        try {
            String loginid = request.getParameter("loginid");
//            String fixedToken = request.getParameter("fixed_token");
            if (StringUtils.isEmpty(loginid)) {
                return JSON.toJSONString(Result.paramErr());
            }
//            if (!StringUtils.equals(fixedToken, DevModeConfig.getPropConfig("api.fixed.token", "f808f256e8df4dfc9f1f90633b194a13").getValue())) {
//                return JSON.toJSONString(Result.tokenErr());
//            }
            // 获取人员ID
            Map<String, String> resMap = DaoUtils.executeQueryToMap("select id, lastname as name, workcode, loginid from hrmresource where loginid = ?", loginid);
            if (resMap == null || resMap.isEmpty()) {
                return JSON.toJSONString(Result.fail("人员不存在"));
            }

            return JSON.toJSONString(Result.ok(resMap));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }

    @GET
    @Path("/user/info/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String hrmUserId(@PathParam("id") String id, @Context HttpServletRequest request,
                            @Context HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(id)) {
                return JSON.toJSONString(Result.paramErr());
            }
            String sql = "select loginid, email, lastname, hrmresource.id, sex, departmentid, hrmresource.subcompanyid1,status ,hrmsubcompany.subcompanyname,hrmdepartment.departmentname " +
                    "from hrmresource " +
                    "left join hrmsubcompany on hrmsubcompany.id = hrmresource.subcompanyid1 " +
                    "left join hrmdepartment on hrmdepartment.id = departmentid where hrmresource.id = ?";
            Map<String, String> map = DaoUtils.executeQueryToMap(sql, id);
            if (map == null || map.isEmpty()) {
                return JSON.toJSONString(Result.fail("用户不存在"));
            }
            // 根据人员ID获取人员信息
            return JSON.toJSONString(Result.ok(map));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }

    // 部门下所有人员
    @GET
    @Path("/dept/userlist/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String hrmDeptId(@PathParam("id") String id, @Context HttpServletRequest request,
                            @Context HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(id)) {
                return JSON.toJSONString(Result.paramErr());
            }
            List<Map<String, String>> mapList = DaoUtils.executeQueryToMapList("select loginid, email, lastname, hrmresource.id, sex, " +
                    "departmentid, hrmresource.subcompanyid1,status ,hrmsubcompany.subcompanyname,hrmdepartment.departmentname,workcode " +
                    "from hrmresource " +
                    "left join hrmsubcompany on hrmsubcompany.id = hrmresource.subcompanyid1 " +
                    "left join hrmdepartment on hrmdepartment.id = departmentid " +
                    "where hrmdepartment.id = ?", id);
            return JSON.toJSONString(Result.ok(mapList));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }

}
